package com.picturewatermark.io;

import java.awt.Image;
import java.awt.image.RenderedImage;
import java.io.File;
import java.io.IOException;

import javax.imageio.ImageIO;

import org.apache.log4j.Logger;

import com.picturewatermark.exception.DirectoryPathException;
import com.picturewatermark.exception.FileExistsException;
import com.picturewatermark.util.BufferedImageConverter;

public class ImageFileHandler {
	private static final Logger LOG = Logger.getLogger(ImageFileHandler.class);

	private ImageFileHandler() {

	}

	public static Image loadImage(final String path) throws IOException {
		return loadImage(new File(path));
	}

	public static Image loadImage(final File file) throws IOException {
		LOG.debug("Path: " + file.getPath());
		if (file.isDirectory()) {
			throw new DirectoryPathException();
		}
		return ImageIO.read(file);
	}

	public static void saveImage(final Image image, final String path,
			final boolean overwrite) throws IOException {
		saveImage(image, new File(path), overwrite);
	}

	public static void saveImage(final Image image, final File file,
			final boolean overwrite) throws IOException {
		LOG.debug("Path: " + file.getPath());
		if (file.isDirectory()) {
			throw new DirectoryPathException();
		}
		if (!overwrite) {
			if (file.exists()) {
				throw new FileExistsException();
			}
		}
		RenderedImage rimage = BufferedImageConverter.getBufferedImage(image);
		ImageIO.write(rimage, "", file);
	}
}
